package dao;

import data.Manager;
import data.Student;
import data.Teacher;
import service.DbConnect;
import service.Tool;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class TeacherDao {
    private static DbConnect<Teacher> c=new DbConnect();
    private static Teacher teacher=new Teacher();
    public static List listAll(){
        try {
            return c.selectList("select * from teacher",teacher);
        }
        catch (Exception e){
            System.out.println("错误"+e.getMessage());
            return null;
        }
    }

    public static Teacher one(int id){
        try{
            return c.selectOne("select * from teacher where id="+id,teacher);
        }catch (Exception e){
            System.out.println("错误"+e.getMessage());
            return null;
        }
    }

    public static boolean add(Teacher t) throws Exception {
        String sql="insert into teacher (name,user,pwd) values"+t.simplSql();
        return c.execute(sql);
    }

    public static boolean del(int id) throws Exception{
        String sql="delete table teacher where id="+id;
        return c.execute(sql);
    }
    public static boolean edit(String type,String val,int id){
        try {
            String sql="update teacher set ?=? where id=?";
            PreparedStatement preparedStatement = c.preparedStatement(sql);
            preparedStatement.setString(1,type);
            preparedStatement.setString(2,val);
            preparedStatement.setInt(3,id);
            c.que(preparedStatement);
            return true;
        } catch (SQLException e) {
            System.out.println("错误："+e.getMessage());
            return false;
        }
    }

    public static String login(Teacher m) throws Exception {
        Teacher manager = c.selectOne("select * from manager where user=" + m.getUser() + " and pwd=" + m.getPwd(), m);
        if(manager==null)
            return null;
        else{
            String session= Tool.session();
            insertToken(manager.getId(),session);
            return session;
        }
    }

    public static void insertToken(int id,String session) throws Exception {
        String sql="update teacher set session="+ session+" where id="+id;
        c.execute(sql);
    }
}
